<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width" charset="UTF-8"/>
    <title>房间系统测试</title>

    <style type="text/css">
        .style1 {
            width: 300px;
            height: 20px;
            text-align: left;
            border: 0;
        }

        .style2 {
            width: 300px;
            height: 20px;
            text-align: right;
            border: 0;
            color: blue;
        }

        .style3 {
            width: 300px;
            height: 20px;
            text-align: left;
            border: 0;
            color: red;
        }
    </style>
</head>

<body>
<div>
    WebSocket服务器地址：<input type="text" id="wsUrl" value="ws://localhost:8080/ws"/><br>
    <input type="button" id="btnConnection" value="连接">&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" id="btnClose" value="断开"><br><br>

    用户ID：&nbsp;&nbsp;&nbsp;<input type="text" id="userId"/><br>
    用户昵称：<input type="text" id="nickname"/><br>
    房间ID：&nbsp;&nbsp;&nbsp;<input type="text" id="roomId"/><br>
    <input type="button" id="loginRoomReq" value="登录房间">&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" id="logoutRoomReq" value="退出房间"><br><br>

    发消息：<input type="text" id="message"/>
    <input type="button" id="TalkMsgReq" value="发送"/><br><br>

    聊天消息：&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" id="clear" value="清除"><br>
    <form id='msgForm'></form>
</div>

<script src="../sockjs.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../math.uuid.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
    var sock;
    var userId;
    var roomId;
    var autoId = 1;
    var taskId;

    var array = new Array(10);
    array[0] = "斗牛大神";
    array[1] = "二B青年";
    array[2] = "天字一号";
    array[3] = "诸葛小明";
    array[4] = "飞猪一号";
    array[5] = "瞄了个咪";
    array[6] = "赌神";
    array[7] = "赌只是浮云";
    array[8] = "唯命是赌";
    array[9] = "谁是英雄";

    function getRandomNickname() {
        return array[Math.uuid(1, 10)];
    }

    $(function () {
        $("#userId").val(Math.uuid(6, 10));
        $("#nickname").val(getRandomNickname());
        $("#roomId").val(10000);
    });

    $("#btnClose").click(function () {
        sock.close();
    });

    $("#clear").click(function () {
        console.log("清理表单");
        $('#msgForm').empty();
    });

    $("#btnConnection").click(function () {
        var wsUrl = userId = $("#wsUrl").val();
        // sock = new SockJS(wsUrl);
        sock = new WebSocket(wsUrl);

        sock.onopen = function () {
            createMsgText("系统信息：socket open succeed!", 3);

            //心跳定时任务
            taskId = setInterval(heartbeatReq, 30000);
        };

        sock.onmessage = function (e) {
            console.log('message: ' + e.data);
            var resp = JSON.parse(e.data);

            var msgCode = resp.header.msgCode;
            var moduleId = resp.header.moduleId;
            var resCode = resp.resCode;
            // var userId = resp.reqData.userId;

            if (moduleId === 30000) {
                switch (msgCode) {
                    case 30001:
                        createMsgText("系统信息：用户" + resp.reqData.userId + "进入了房间！", 3);
                        break;
                    case 30002:
                        if (resCode === 0) {
                            createMsgText("系统信息：登录成功！", 3);
                        } else {
                            createMsgText("系统信息：登录失败！", 3);
                        }
                        break;
                    case 30003:
                        createMsgText("系统信息：用户" + resp.reqData.userId + "退出了房间！", 3);
                        break;
                    case 30004:
                        if (resCode === 0) {
                            createMsgText("系统信息：退出成功！", 3);
                        } else {
                            createMsgText("系统信息：退出失败！", 3);
                        }
                        break;
                    case 30005:
                        createMsgText("用户" + resp.reqData.userId + ":" + resp.reqData.message, 2);
                        break;
                    case 30006:
                        if (resCode !== 0) {
                            createMsgText("系统信息：" + resp.resMsg, 3);
                        }
                }
            } else if (moduleId === 10000) {
                console.log("收到心跳响应...")
            } else {
                alert("发生未知错误！")
            }
        };

        sock.onclose = function () {
            createMsgText("系统信息：socket close...", 3);
            clearInterval(taskId);
        };
    });

    /**
     * 登录房间
     */
    $("#loginRoomReq").click(function () {
        userId = $("#userId").val();
        roomId = $("#roomId").val();
        var nickname = $("#nickname").val();

        var req = {
            "header": {
                "moduleId": 30000,
                "msgCode": 30001,
                "requestId": Math.uuid(6, 10)
            },
            "reqData": {
                "icon": "http://www.baidu.com",
                "nickname": nickname,
                "roomId": roomId,
                "userId": userId
            }
        };

        sock.send(JSON.stringify(req));
    });


    /**
     * 退出房间
     */
    $("#logoutRoomReq").click(function () {
        userId = $("#userId").val();
        roomId = $("#roomId").val();

        var req = {
            "header": {
                "moduleId": 30000,
                "msgCode": 30003,
                "requestId": Math.uuid(6, 10)
            },
            "reqData": {
                "roomId": roomId,
                "userId": userId
            }
        };

        sock.send(JSON.stringify(req));
    });

    /**
     * 发送消息
     */
    $("#TalkMsgReq").click(function () {
        userId = $("#userId").val();
        roomId = $("#roomId").val();
        var message = $("#message").val();

        var req = {
            "header": {
                "moduleId": 30000,
                "msgCode": 30005,
                "requestId": Math.uuid(6, 10)
            },
            "reqData": {
                "message": message,
                "roomId": roomId,
                "userId": userId
            }
        };
        sock.send(JSON.stringify(req));

        createMsgText(message + "：我", 1);
    });

    /**
     * 发送心跳
     */
    function heartbeatReq() {
        var req = {
            "header": {
                "moduleId": 10000,
                "msgCode": 10003,
                "requestId": Math.uuid(6, 10)
            },
            "reqData": {}
        };
        sock.send(JSON.stringify(req));
    }

    function createMsgText(message, type) {
        var input = document.createElement('input');  //创建input节点
        input.setAttribute('type', 'text');  //定义类型是文本输入
        input.setAttribute('value', String(message));
        if (type === 1) { //自己
            input.setAttribute('class', 'style2');
        } else if (type === 2) {
            input.setAttribute('class', 'style1');
        } else {
            input.setAttribute('class', 'style3');
        }
        document.getElementById('msgForm').appendChild(input); //添加到form中显示

        var br = document.createElement('br');
        document.getElementById('msgForm').appendChild(br);
        autoId++;
    }
</script>

</body>

</html>